<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">日期</label>
        <date-range-picker
          v-model="query.createTime"
          class="date-item"
        />

        <label class="el-form-item-label">名称</label>
        <el-input v-model="query.name" clearable placeholder="名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />

        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">

        <span slot="right">
          <div style="display: inline-block;margin: 0px 2px;">
            <el-upload
              ref="upload"
              v-permission="['admin','property:import']"
              :show-file-list="false"
              :before-upload="beforeupload"
              :on-success="handleSuccessFile"
              :on-error="handleErrorFile"
              :action="baseApi + '/api/property/upload'"
              :headers="headers"
              accept=".xls,.xlsx"
              enctype="multipart/form-data"
            >
              <el-button type="primary" class="filter-item" size="mini" icon="el-icon-upload">导入</el-button>
            </el-upload>
          </div>
          <el-button
            size="mini"
            class="filter-item"
            type="text"
            style="background:#fffffb;"
            @click="downloadModel"
          >
            <svg-icon icon-class="log" />
            下载模板</el-button>
        </span>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="550px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="138px">
          <el-form-item label="资产名称" prop="name">
            <el-input v-model="form.name" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="资产金额" prop="price">
            <el-input v-model="form.price" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="相关资料">
            <el-upload
              class="upload-demo"
              :action="fileUploadApi + '?name=' + fileName"
              :on-preview="handlePreview"
              :before-upload="onBeforeUpload"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="3"
              :headers="headers"
              :on-exceed="handleExceed"
              :file-list="form.fileList"
            >
              <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              <div slot="tip" class="el-upload__tip">只能上传word/pdf文件，且不超过10MB</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" show-summary sum-text="总计" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column prop="price" label="资产" align="center">
          <template slot-scope="scope">
            {{ scope.row.price+"元" }}
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="附件资料" align="center">
          <template v-if="scope.row.filePath" slot-scope="scope">
            <!-- {{ scope.row.filePath }} -->
            <ReadFile v-if="scope.row.filePath" :file-path="scope.row.filePath" />

            <div v-else style="color:#E6A23C;">
              <span>未上传文件</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建日期" align="center" />

        <el-table-column v-if="checkPer(['admin','property:edit','property:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { download } from '@/api/data'
import crudProperty from '@/api/property'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import DateRangePicker from '@/components/DateRangePicker'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import ReadFile from '@/views/components/ReadFile'
import { downloadFile } from '@/utils/index'

const defaultForm = { id: null, name: null, price: null, createTime: null, updateTime: null, fileName: null, filePath: null, fileList: [] }
export default {
  name: 'Property',
  components: { pagination, crudOperation, rrOperation, udOperation, DateRangePicker, ReadFile },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '资产', url: 'api/property', idField: 'id', sort: 'id,desc', crudMethod: { ...crudProperty }})
  },
  data() {
    return {
      fileName: null,
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'property:add'],
        edit: ['admin', 'property:edit'],
        del: ['admin', 'property:del']
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }

        ],
        price: [
          { required: true, message: '金钱不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '名称' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterToCU](crud, form) {
      if (this.form.filePath) {
        var files = this.form.filePath.split('|')

        for (var j = 0; j < files.length; j++) {
          if (files[j]) {
            var res = files[j].split('/')
            this.form.fileList.push({
              'name': res[3],
              'url': this.baseApi + files[j],
              response: { 'realName': res[3], 'type': res[2] }
            })
          }
        }
      }
    },

    /** 导入模板 */
    beforeupload(file) {
      const isLt1M = file.size / 1024 / 1024 < 100
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.fileName = file.name
      return isLt1M
    },
    /** 导入模板的成功状态 */
    handleSuccessFile(res, file) {
      if (res.state === 'success') {
        this.$message({
          message: res.info,
          type: 'success'
        })
        this.crud.toQuery()
      } else {
        this.$message.error(res.message)
      }
    },
    /** 失败状态 */
    handleErrorFile(file) {
      this.$message.error('数据导入失败！')
    },
    /** 下载模板 */
    downloadModel() {
      var params = { }
      params.id = -1
      download(this.crud.url + '/export', params).then(result => {
        downloadFile(result, '资产模板', 'xlsx')
      })
    },

    /* 上传文件的一系列方法*/
    onBeforeUpload(file) {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isFile = (extension === 'doc' || extension === 'docx' || extension === 'pdf')
      if (!isFile) {
        this.$message.error('上传文件只能是Word/PDF格式!')
      }
      const isLt1M = file.size / 1024 / 1024 < 100
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.fileName = file.name
      return isFile && isLt1M
    },
    handleSuccess(response, file, fileList) {
      console.log(file)
      // this.form.filePath = file.response.path
      this.form.fileName = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.filePath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
        this.form.fileName += fileList[i].response.realName + '|'
      }
      var fileLength = this.form.filePath.length
      if (fileLength > 1) {
        this.form.filePath = this.form.filePath.substring(0, fileLength - 1)
        this.form.fileName = this.form.fileName.substring(0, fileLength - 1)
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(file, fileList) {
      this.form.filePath = ''
      this.form.fileName = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.filePath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
        this.form.fileName += fileList[i].response.realName + '|'
      }
      var fileLength = this.form.filePath.length
      if (fileLength > 1) {
        this.form.filePath = this.form.filePath.substring(0, fileLength - 1)
        this.form.fileName = this.form.fileName.substring(0, fileLength - 1)
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    handlePreview(file) {
      console.log(file)
    }

  }

}
</script>

<style scoped>

.eladmin-upload{
  width: 270px;

}
</style>
